import { ref, reactive } from 'vue'
import type { Ref } from 'vue'
import type { LoginResult } from '@/types/userInfo'
import type { PageParams } from '@/types/common'
import type { MsgData } from '@/types/userInfo'
import { useUserInfoStore } from '@/stores'
import { ImageAddHttp, formatTimestamp } from '@/utils/index'
import { onLoad } from '@dcloudio/uni-app'
import {
  getUserInfo,
  getUserMsg,
  getLike,
  getCollect,
  getMsgUnreadApi,
  deleteMessage,
} from '@/api/user'

export function useScript(modal: Ref) {
  const dataList = ref<MsgData[]>([])
  const del_id = ref<number>(0)
  const isLoad = ref(false)
  const msgNum = ref<number>(0) // 未读消息数
  const isRefreshing = ref<boolean>(false)
  const refreshEmabled = ref(false)
  const selfInfo = ref(useUserInfoStore().profile)
  const userInfo = ref<LoginResult>()
  const ModelContent = ref<string>('确定删除该信息吗？')
  const mes_typpe = ref<number>(0) // 0:消息 1:收藏 2:点赞
  const pagination = reactive<PageParams>({
    pageSize: 8,
    page: 1,
    total: 0,
    order: 'desc',
  })

  async function getMeg(reset = false) {
    const params = {
      page: pagination.page,
      limit: pagination.pageSize,
      order: pagination.order,
    }
    isLoad.value = true

    let result
    switch (mes_typpe.value) {
      case 0:
        result = await getUserMsg(userInfo.value!.id, pagination)
        break
      case 1:
        result = await getCollect(params)
        break
      case 2:
        result = await getLike(params)
        break
    }
    if (result?.code) {
      // 新添加进 dataList中
      if (reset) dataList.value.length = 0
      result.data.list.forEach((item: MsgData) => {
        const avatar = ImageAddHttp(item.avatar as string)
        dataList.value.push({
          id: item.id,
          user_id: item.user_id,
          avatar: avatar,
          nickname: item.nickname,
          username: `@${item.username}`,
          createtime: formatTimestamp(item!.createtime as number, 'yyyy-MM-dd HH:mm:ss'),
          content: item.content,
          is_liked: item.is_liked,
          is_collected: item.is_collected,
        })
      })
      // 更新总数
      pagination.total = result.data.total
      pagination.page = result.data.currentPage
      if (!refreshEmabled.value) {
        refreshEmabled.value = true
      }
    }
    isLoad.value = false
  }

  async function confirm() {
    if (!del_id.value) return
    const res = await deleteMessage(del_id.value)
    if (res.code) {
      dataList.value = dataList.value.filter((item) => item.id !== del_id.value)
      modal.value.close()
    }
  }

  async function refreshComments() {
    if (isLoad.value) return
    pagination.page = 1
    isRefreshing.value = true
    await getMeg(true)
    isRefreshing.value = false
  }

  async function getMsgUnread() {
    const res = await getMsgUnreadApi()
    if (res.code) {
      msgNum.value = res.data as unknown as number
    }
  }

  const Back = async () => {
    uni.navigateBack()
  }

  const allMsg = async () => {
    mes_typpe.value = 0
    await refreshComments()
  }

  const onCollect = async () => {
    mes_typpe.value = 1
    await refreshComments()
  }

  const onLike = async () => {
    mes_typpe.value = 2
    await refreshComments()
  }

  const publish = async () => {
    uni.redirectTo({
      url: '/pages/publish/publish',
    })
  }

  const newMsg = async () => {
    if (msgNum.value === 0) {
      uni.showToast({
        title: '没有新消息',
        icon: 'none',
      })
      return
    }
    uni.redirectTo({
      url: '/pages/message/newmsg',
    })
  }

  async function renderInfo(options: any) {
    if (options && options.id && options.id !== selfInfo.value?.id) {
      const res = await getUserInfo({ id: options.id })
      if (res.code && res.data) {
        userInfo.value = res.data
      }
    } else {
      userInfo.value = selfInfo.value
    }
    await Promise.all([refreshComments(), getMsgUnread()])

    setInterval(async () => {
      if (msgNum.value === 0) {
        await getMsgUnread()
      }
    }, 50000)
  }

  async function cardHandle(card: MsgData) {
    console.log(card)
    uni.navigateTo({
      url: `/pages/message/message?id=${card.id}`,
    })
  }

  async function deleteCard(id: number) {
    del_id.value = id
    modal.value.open()
  }

  async function loadMoreComments() {
    if (isLoad.value) return
    if (
      pagination.page !== undefined &&
      pagination.page < Math.ceil((pagination.total ?? 0) / (pagination.pageSize ?? 1))
    ) {
      pagination!.page++
      await getMeg()
    }
  }

  async function gotoUserInfo(id: number) {
    if (id) {
      if (userInfo.value?.id !== id) {
        uni.navigateTo({
          url: `/pages/profile/profile?id=${id}`,
        })
      }
      return
    }
    if (userInfo.value?.id === selfInfo.value?.id) {
      uni.navigateTo({
        url: `/pages/profile/edit?info=1`,
      })
    }
  }

  onLoad(async (options) => {
    await renderInfo(options)
  })

  return {
    dataList,
    msgNum,
    mes_typpe,
    isRefreshing,
    userInfo,
    selfInfo,
    ModelContent,
    refreshEmabled,
    gotoUserInfo,
    loadMoreComments,
    refreshComments,
    Back,
    confirm,
    newMsg,
    allMsg,
    onCollect,
    onLike,
    publish,
    cardHandle,
    deleteCard,
  }
}
